<template>
  <div>
    <el-dialog
      v-model="open"
      :close-on-click-modal="false"
      :title="title"
      width="500px"
      append-to-body
    >
      <el-form
        ref="setFormRef"
        :model="form"
        label-width="80px"
      >
        <el-form-item label="分组名称" prop="groupName">
          <el-input v-model="form.groupName" placeholder="请输入分组名称" />
        </el-form-item>

        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in dicts[DictDirection.通用状态]" :key="dict.dictValue" :label="dict.dictValue">{{ dict.dictLabel }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入..." />
        </el-form-item>
      </el-form>
      <template #footer>
        <div>
          <el-button type="primary" @click="submit">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { ref, getCurrentInstance, watch, defineExpose, defineEmits } from 'vue'
import { ElMessage } from 'element-plus'
import useDicts, { DictDirection } from '@/store/modules/dicts'
import { getGroup, addGroup, updateGroup } from '@/api/basicConfig/productsGroup'

const dicts = useDicts()
dicts.setDicts(DictDirection.通用状态)
let 
  title = ref(''),
  open = ref(false),
  form = ref({
    id: undefined,
    groupName: undefined,
    status: '0',
    remark: undefined,
  }),
  setFormRef = ref(null),
  {
    appContext: {
      config: {
        globalProperties: { $resetForm, $validateForm },
      },
    },
  } = getCurrentInstance()
const emit = defineEmits(['changeList'])
const reset = () => {
  form.value = {
    id: undefined,
    groupName: undefined,
    status: '0',
    remark: undefined,
  }
  $resetForm(setFormRef.value)
}
// 确定新增-修改
const submit = () => {
  $validateForm(setFormRef.value, async () => {
    if (form.value.id == undefined) {
      addGroup(form.value).then((res) => {
        if (res.code == 200) {
          ElMessage.success('新增成功')
          open.value = false
          emit('changeList')
          reset()
        }
      })
    } else {
      updateGroup(form.value).then((res) => {
        if (res.code == 200) {
          ElMessage.success('修改成功')
          open.value = false
          emit('changeList')
          reset()
        }
      })
    }
  })
}
const cancel = () => {
  open.value = false
  reset()
}
const getDetail = (id) => {
  getGroup(id).then((res) => {
    if (res.code == 200) {
      const resList = JSON.parse(JSON.stringify(res.data))
      console.log(resList)
      form.value = resList
      console.log(form.value)
    }
  })
}
watch(open, (v) => {
  if (!v) {
    reset()
    // getDetail(id)
  }
})
defineExpose({
  open,
  title,
  getDetail,
})
</script>
l
